<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { userApi } from '../api/index'

const users = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const isEdit = ref(false)
const searchQuery = ref('')

const userForm = ref({
  id: null,
  username: '',
  password: '',
  name: '',
  email: '',
  phone: '',
  role: 'USER'
})

// 基本验证规则
const baseRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 动态验证规则
const userFormRules = computed(() => {
  // 编辑模式下密码可选，新增模式下密码必填
  const passwordRule = isEdit.value
    ? [{ min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }]
    : [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
      ]
  
  return {
    ...baseRules,
    password: passwordRule
  }
})

const userFormRef = ref(null)

onMounted(async () => {
  await fetchUsers()
})

const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await userApi.getAllUsers()
    users.value = res.data
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加用户'
  isEdit.value = false
  dialogVisible.value = true
}

const handleEdit = (row) => {
  resetForm()
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  userForm.value = {
    id: row.id,
    username: row.username,
    password: '', // 不回显密码
    name: row.name,
    email: row.email || '',
    phone: row.phone || '',
    role: row.role
  }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await userApi.deleteUser(row.id)
      ElMessage.success('删除成功')
      await fetchUsers()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败，请稍后重试')
    }
  }).catch(() => {})
}

const resetForm = () => {
  userForm.value = {
    id: null,
    username: '',
    password: '',
    name: '',
    email: '',
    phone: '',
    role: 'USER'
  }
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 如果是编辑模式且密码为空，则不更新密码
          const userData = { ...userForm.value }
          if (!userData.password) {
            delete userData.password
          }
          await userApi.updateUser(userData.id, userData)
          ElMessage.success('更新成功')
        } else {
          // 确保所有必需字段都有值
          const userData = { ...userForm.value }
          // 添加创建时间和更新时间字段
          const now = new Date().toISOString();
          userData.createdAt = now;
          userData.updatedAt = now;
          
          await userApi.register(userData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        await fetchUsers()
      } catch (error) {
        console.error('操作失败:', error)
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else if (error.response && error.response.status === 400) {
          ElMessage.error('操作失败：请求数据无效，可能用户名已存在或必填字段缺失')
        } else {
          ElMessage.error('操作失败，请稍后重试')
        }
      }
    }
  })
}

// 过滤用户列表
const filteredUsers = computed(() => {
  if (!searchQuery.value) return users.value
  
  const query = searchQuery.value.toLowerCase()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(query) || 
    (user.name && user.name.toLowerCase().includes(query)) ||
    (user.role && user.role.toLowerCase().includes(query))
  )
})
</script>

<template>
  <div class="user-management-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAdd">添加用户</el-button>
    </div>
    
    <el-card shadow="hover" class="filter-card">
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名、姓名或角色"
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="table-card">
      <el-table
        v-loading="loading"
        :data="filteredUsers"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="电话" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'ADMIN' ? 'danger' : 'success'">
              {{ scope.row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      append-to-body
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            show-password
            :placeholder="isEdit ? '不修改请留空' : '请输入密码'"
          />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input {
  max-width: 400px;
}

.table-card {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .search-input {
    width: 100%;
    max-width: none;
  }
}
</style> 